<template>
  <view class="container">
    <!-- 搜索栏 -->
    <view class="search-bar">
      <view class="search-input">
        <uni-icons type="search" size="18" color="#999"></uni-icons>
        <input 
          type="text" 
          placeholder="搜索公司名称..." 
          v-model="keyword"
          @confirm="doSearch"/>
      </view>
      <text class="cancel" @click="cancelSearch">取消</text>
    </view>
    
    <!-- 搜索历史 -->
    <view class="search-history" v-if="!isSearching && historyList.length > 0">
      <view class="history-header">
        <text class="title">搜索历史</text>
        <text class="clear" @click="clearHistory">清除历史</text>
      </view>
      <view class="history-tags">
        <text class="tag" v-for="(item, index) in historyList" :key="index" @click="searchWithHistory(item)">
          {{ item }}
        </text>
      </view>
    </view>
    
    <!-- 热门搜索 -->
    <view class="hot-search" v-if="!isSearching">
      <view class="hot-header">
        <text class="title">热门搜索</text>
      </view>
      <view class="hot-tags">
        <text class="tag" v-for="(item, index) in hotSearchList" :key="index" @click="searchWithHot(item)">
          {{ item }}
        </text>
      </view>
    </view>
    
    <!-- 搜索结果 -->
    <view class="search-results" v-if="isSearching">
      <!-- 加载中 -->
      <view class="loading" v-if="loading">
        <uni-icons type="spinner" size="24" color="#36D" class="loading-icon" :animation="true"></uni-icons>
        <text class="loading-text">正在搜索中...</text>
      </view>
      
      <view v-else>
        <view class="results-header">
          <text class="count">找到 {{ filteredCompanies.length }} 个结果</text>
        </view>
      
      <view class="company-list">
        <view class="company-item" v-for="(company, index) in filteredCompanies" :key="index" 
          @click="handleCompanySelect(company)">
          <image :src="company.logo" mode="widthFix" class="company-logo"></image>
          <view class="company-info">
            <view class="company-name">
              <text>{{ company.name }}</text>
              <text class="highlight" v-if="company.highlight">{{ company.highlight }}</text>
            </view>
            <view class="company-desc">{{ company.industry }} · {{ company.location }}</view>
            <view class="company-rating">
              <uni-icons type="star" size="14" color="#FFCC00"></uni-icons>
              <text class="rating-num">{{ company.rating }}</text>
              <text class="review-count">({{ company.reviewCount }}条评价)</text>
            </view>
          </view>
          <uni-icons type="arrowright" size="18" color="#ccc" class="arrow"></uni-icons>
        </view>
      </view>
      
        <view class="no-result" v-if="filteredCompanies.length === 0">
          <uni-icons type="search" size="48" color="#ccc"></uni-icons>
          <text class="no-result-text">没有找到相关公司</text>
          <text class="suggestion">请尝试其他关键词</text>
		            <button class="create-company-btn" @click="gotoCreateCompany">搜索不到理想结果？创建新公司</button>

        </view>
      </view>
    </view>
  </view>
</template>

<script>
import { getCompanyList, getCompanyOverallScore, getUserReviews } from '@/api/company.js';

export default {
  data() {
    return {
      keyword: '',
      isSearching: false,
      selectMode: false, // 是否为选择公司模式（从发布评价页面进入）
      historyList: ['比特', '昆汀考情', '考考', '小富'],
      hotSearchList: ['比特',  '考考',   '小富'],
      companies: [], // 将从接口获取
      loading: false, // 加载状态
      filteredCompanies: []
    };
  },
  onLoad(options) {
    if (options.keyword) {
      this.keyword = options.keyword;
      this.doSearch();
    }
    
    if (options.selectMode === 'true' || options.selectMode === true) {
      this.selectMode = true;
    }
  },
  methods: {
    // 获取企业综合评分
    async getCompanyRating(companyId) {
      try {
        const res = await getCompanyOverallScore({
          companyId,
          pageNum: 1,
          pageSize: 1
        });
        if (res && res.data) {
          let data = res.data;
          // 处理不同可能的数据结构
          if (!Array.isArray(data)) {
            if (data.list) data = data.list;
            else if (data.rows) data = data.rows;
            else return 0;
          }
          
          // 查找综合评分
          if (data.length > 0 && data[0].overallScore !== undefined) {
            return parseFloat(data[0].overallScore);
          }
        }
      } catch (error) {
        console.error(`获取企业 ${companyId} 的综合评分失败:`, error);
      }
      return 0;
    },
    
    // 获取企业评价数量
    async getCompanyReviewCount(companyId) {
      try {
        const res = await getUserReviews({
          companyId,
          pageNum: 1,
          pageSize: 1
        });
        if (res && res.total !== undefined) {
          return res.total;
        } else if (res && res.rows) {
          return res.rows.length;
        }
      } catch (error) {
        console.error(`获取企业 ${companyId} 的评价数量失败:`, error);
      }
      return 0;
    },
    
    async doSearch() {
      if (!this.keyword.trim()) return;
      
      this.isSearching = true;
      this.loading = true;
      this.filteredCompanies = [];
      
      try {
        // 调用企业列表接口，传入关键词参数
        const params = {
          pageNum: 1,
          pageSize: 50, // 一次获取较多结果
          companyName: this.keyword.trim() // 使用关键词搜索
        };
        
        const res = await getCompanyList(params);
        
        if (res && res.rows && res.rows.length > 0) {
          // 转换数据格式
          const companies = res.rows.map(company => ({
            id: company.companyId || company.id,
            name: company.companyName || '未知公司',
            logo: company.logo_url || company.logoUrl || '/static/images/default-company.png',
            industry: company.companyIndustry || '未知行业',
            location: company.location ? 
              `${company.location.city || company.location.province || '未知城市'}` : 
              '未知地址',
            rating: 0, // 将在后面获取
            reviewCount: 0 // 将在后面获取
          }));
          
          // 为每家公司获取综合评分和评价数量
          for (const company of companies) {
            // 并行获取评分和评价数量
            const [rating, reviewCount] = await Promise.all([
              this.getCompanyRating(company.id),
              this.getCompanyReviewCount(company.id)
            ]);
            
            company.rating = rating || 0;
            company.reviewCount = reviewCount || 0;
          }
          
          this.companies = companies;
          this.filteredCompanies = companies;
        }
        
        // 添加到搜索历史（去重）
        if (!this.historyList.includes(this.keyword)) {
          this.historyList.unshift(this.keyword);
          // 限制历史记录数量
          if (this.historyList.length > 10) {
            this.historyList.pop();
          }
        }
      } catch (error) {
        console.error('搜索公司失败:', error);
        uni.showToast({
          title: '搜索失败，请稍后重试',
          icon: 'none'
        });
        
        // 使用默认数据作为降级方案
        this.filteredCompanies = [
          {
            id: 1,
            name: '比特',
            logo: '/static/c1.png',
            industry: '互联网',
            location: '北京',
            rating: 4.2,
            reviewCount: 1256
          },
          {
            id: 2,
            name: '昆汀考情',
            logo: '/static/c2.png',
            industry: '互联网',
            location: '深圳',
            rating: 4.5,
            reviewCount: 2345
          }
        ];
      } finally {
        this.loading = false;
      }
    },
    searchWithHistory(keyword) {
      this.keyword = keyword;
      this.doSearch();
    },
    searchWithHot(keyword) {
      this.keyword = keyword;
      this.doSearch();
    },
    clearHistory() {
      uni.showModal({
        title: '提示',
        content: '确定要清除所有搜索历史吗？',
        success: res => {
          if (res.confirm) {
            this.historyList = [];
          }
        }
      });
    },
    cancelSearch() {
      uni.navigateBack();
    },
    handleCompanySelect(company) {
      if (this.selectMode) {
        // 选择公司模式，返回公司信息
        uni.redirectTo({
          url: `/pages/review/publish?companyId=${company.id}&companyName=${encodeURIComponent(company.name)}`
        });
      } else {
        // 普通模式，进入公司详情页
        uni.navigateTo({
          url: `/pages/company/detail?id=${company.id}`
        });
      }
    
	},
	    gotoCreateCompany() {
	      // 记录当前的搜索关键词，传递给创建公司页面
	      uni.navigateTo({
	        url: `/pages/company/create?keyword=${encodeURIComponent(this.keyword || '')}&fromSearch=true`
	      });
	    }
  }
};
</script>

<style scoped>
.container {
  display: flex;
  flex-direction: column;
  min-height: 100vh;
  background-color: #f5f5f5;
}

.search-bar {
  display: flex;
  align-items: center;
  padding: 10px 15px;
  background-color: #fff;
  border-bottom: 1px solid #eee;
}

.search-input {
  flex: 1;
  display: flex;
  align-items: center;
  background-color: #f5f5f5;
  border-radius: 20px;
  padding: 8px 15px;
}

.search-input input {
  flex: 1;
  margin-left: 5px;
  font-size: 14px;
  color: #333;
}

.cancel {
  font-size: 16px;
  color: #333;
  margin-left: 15px;
}

.search-history, .hot-search {
  padding: 15px;
  background-color: #fff;
  margin-bottom: 10px;
}

.history-header, .hot-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.title {
  font-size: 16px;
  color: #333;
  font-weight: bold;
}

.clear {
  font-size: 14px;
  color: #666;
}

.history-tags, .hot-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.tag {
  display: inline-block;
  padding: 8px 15px;
  background-color: #f5f5f5;
  border-radius: 20px;
  font-size: 14px;
  color: #333;
}

.search-results {
  flex: 1;
  background-color: #fff;
}

.results-header {
  padding: 15px;
  border-bottom: 1px solid #eee;
}

.count {
  font-size: 14px;
  color: #666;
}

.company-list {
  padding: 10px 0;
}

.company-item {
  display: flex;
  align-items: center;
  padding: 15px;
  border-bottom: 1px solid #eee;
}

.company-item:last-child {
  border-bottom: none;
}

.company-logo {
  width: 60px;
  height: 60px;
  border-radius: 8px;
  margin-right: 15px;
}

.company-info {
  flex: 1;
}

.company-name {
  font-size: 16px;
  font-weight: bold;
  color: #333;
  margin-bottom: 5px;
  display: flex;
  align-items: center;
}

.highlight {
  font-size: 12px;
  color: #F66;
  background-color: #FFF5F5;
  padding: 2px 5px;
  border-radius: 3px;
  margin-left: 8px;
}

.company-desc {
  font-size: 14px;
  color: #666;
  margin-bottom: 5px;
}

.company-rating {
  display: flex;
  align-items: center;
}

.rating-num {
  font-size: 14px;
  color: #FF6600;
  margin-left: 3px;
}

.review-count {
  font-size: 12px;
  color: #999;
  margin-left: 5px;
}

.arrow {
  color: #ccc;
}

.no-result {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 50px 0;
}

.no-result-text {
  font-size: 16px;
  color: #666;
  margin-top: 20px;
  margin-bottom: 10px;
}

.suggestion {
  font-size: 14px;
  color: #999;
}

/* 加载状态样式 */
.loading {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 50px 0;
}

.loading-icon {
  margin-bottom: 10px;
}

.loading-text {
  font-size: 14px;
  color: #666;
}
.create-company-btn {
  margin-top: 20px;
  padding: 10px 30px;
  background-color: #36D;
  color: white;
  border: none;
  border-radius: 20px;
  font-size: 14px;
  line-height: 1.5;
}
</style>
